package com.wzcl.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.wzcl.app.dao.model.Activity;
import com.wzcl.app.dao.model.HomeMassage;
import com.wzcl.app.dao.repository.HomeMassageRepository;
import com.wzcl.app.model.common.BusinessException;
import com.wzcl.app.model.common.CodeMsg;
import com.wzcl.app.model.common.MyPage;
import com.wzcl.app.model.dto.HomeMassageDto;
import com.wzcl.app.service.HomeMassageService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@Service
public class HomeMassageServiceImpl implements HomeMassageService {

    @Autowired
    private HomeMassageRepository repository;

    @Override
    @CacheEvict(value = "HomeMassage", allEntries = true)
    public HomeMassage addHomeMassage(HomeMassageDto homeMassageDto) {
        HomeMassage homeMassage = new HomeMassage();
        BeanUtils.copyProperties(homeMassageDto, homeMassage);
        return repository.save(homeMassage);
    }

    @Override
    @CacheEvict(value = "HomeMassage", allEntries = true)
    public HomeMassage delHomeMassageById(Integer id) {
        //校验获取
        HomeMassage homeMassage = getAndCheckById(id);
        //删除
        log.info("HomeMassage:{} Physical deletion", JSON.toJSONString(homeMassage));
        repository.delete(homeMassage);
        return homeMassage;
    }

    @Override
    @CacheEvict(value = "HomeMassage", allEntries = true)
    public HomeMassage updateHomeMassage(HomeMassageDto homeMassageDto) {
        //校验获取
        HomeMassage homeMassage = getAndCheckById(homeMassageDto);
        //修改
        BeanUtils.copyProperties(homeMassageDto, homeMassage);
        return repository.save(homeMassage);
    }

    @Override
    @CacheEvict(value = "HomeMassage", allEntries = true)
    public List<HomeMassage> updateHomeMassageList(String type, String groupName, List<HomeMassageDto> homeMassageDtoList) {
        //删除原先的
        List<HomeMassage> homeMassageList = repository.findAllByTypeAndGroupName(type, groupName);
        if (homeMassageList != null && homeMassageList.size() > 0) {
            repository.deleteAll(homeMassageList);
        }
        //新增修改来的
        if (homeMassageDtoList != null && homeMassageDtoList.size() > 0) {
            List<HomeMassage> collect = homeMassageDtoList.stream().map(homeMassageDto -> {
                HomeMassage homeMassage = new HomeMassage();
                BeanUtils.copyProperties(homeMassageDto, homeMassage);
                return homeMassage;
            }).collect(Collectors.toList());
            return repository.saveAll(collect);
        }
        return null;
    }

    @Override
    public HomeMassage getHomeMassageById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public HomeMassage getAndCheckById(Integer id) {
        if (id == null) {
            throw new BusinessException(CodeMsg.MUST_BE_NOT_NULL, "缺少首页Id");
        }
        HomeMassage homeMassage = getHomeMassageById(id);
        if (homeMassage == null) {
            throw new BusinessException(CodeMsg.HOME_MASSAGE_NOT_EXIST);
        }
        return homeMassage;
    }

    @Override
    @Cacheable(value = "HomeMassage", keyGenerator = "cacheKeyGenerator")
    public List<HomeMassage> getHomeMassageList(HomeMassageDto homeMassageDto) {
        return repository.findAll(getSpecification(homeMassageDto), homeMassageDto.getSort());
    }

    @Override
    @Cacheable(value = "HomeMassage", keyGenerator = "cacheKeyGenerator")
    public MyPage<HomeMassage> getHomeMassagePage(HomeMassageDto homeMassageDto) {
        Page<HomeMassage> all = repository.findAll(getSpecification(homeMassageDto), homeMassageDto.getPageable());
        ArrayList<HomeMassage> list = new ArrayList<>(all.getContent());
        Collections.reverse(list);
        MyPage<HomeMassage> myPage = new MyPage<>();
        myPage.setContent(list);
        myPage.setTotalElements(all.getTotalElements());
        return myPage;
    }

    private Specification<HomeMassage> getSpecification(HomeMassageDto HomeMassageDto) {
        return new Specification<HomeMassage>() {
            @Override
            public Predicate toPredicate(Root<HomeMassage> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<Predicate>();
                if (StringUtils.isNotBlank(HomeMassageDto.getType())) {
                    predicates.add(criteriaBuilder.equal(root.get("type"), HomeMassageDto.getType()));
                }
                if (StringUtils.isNotBlank(HomeMassageDto.getGroupName())) {
                    predicates.add(criteriaBuilder.equal(root.get("groupName"), HomeMassageDto.getGroupName()));
                }
                if (HomeMassageDto.getIsDefault() != null) {
                    predicates.add(criteriaBuilder.equal(root.get("isDefault"), HomeMassageDto.getIsDefault()));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
    }
}
